package com.ll.sender;

import java.net.URI;
import java.net.URISyntaxException;

import microsoft.exchange.webservices.data.core.ExchangeService;
import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion;
import microsoft.exchange.webservices.data.core.exception.service.local.ServiceLocalException;
import microsoft.exchange.webservices.data.core.service.item.EmailMessage;
import microsoft.exchange.webservices.data.credential.ExchangeCredentials;
import microsoft.exchange.webservices.data.credential.WebCredentials;
import microsoft.exchange.webservices.data.property.complex.MessageBody;

/**
 * exchange邮件发送
 * 
 * @author liudawei
 * @date 2016年4月14日下午3:48:50
 */
public class EWSSendMail {

	private static ExchangeService service;

	public EWSSendMail(final String smtpHostName, final String username, final String password)
			throws URISyntaxException, Exception {
		service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
		ExchangeCredentials credentials = new WebCredentials(username, password);
		service.setCredentials(credentials);
		service.setUrl(new URI("https://" + smtpHostName + "/ews/Exchange.asmx"));
		// service.autodiscoverUrl("emailAddress");
	}

	public void send(String recipient, String subject, Object content) throws ServiceLocalException, Exception {
		EmailMessage msg = new EmailMessage(service);
		msg.setSubject(subject);
		msg.setBody(MessageBody.getMessageBodyFromText(content.toString()));
		msg.getToRecipients().add(recipient);
		msg.send();
	}

	public static void main(String[] args) throws Exception {
		String username = "bioservice@ronglian.com";
		String password = "1234@abcd";
		String smtpHostName = "mail.ronglian.com";
		ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
		ExchangeCredentials credentials = new WebCredentials(username, password);
		service.setCredentials(credentials);
		service.setUrl(new URI("https://" + smtpHostName + "/ews/Exchange.asmx"));
		EmailMessage msg = new EmailMessage(service);
		msg.setSubject("主题");
		msg.setBody(MessageBody.getMessageBodyFromText("内容"));
		msg.getToRecipients().add("598156412@qq.com");
		msg.send();
	}

}
